import React,{ useEffect,useState } from 'react';
import { Button, Form, Input, message,Select } from 'antd';
import {addArticleApi,getArticleTagListApi} from '@/api/requestApi'
import { useNavigate } from 'react-router-dom';
import NewsEditor from '@/components/editor/NewsEditor';

const layout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 22 },
};
// 表单元素的校验规则提示信息
const validateMessages = {
  required: '${label} 不能为空',
};


const Add: React.FC = () => {
  const navigate = useNavigate();
  const [tagList,setTagList] = useState([]) // 根据接口文档中的返回数据结构,默认设置为空数组
  const [articleContent,setArticleContent] = useState('')

  useEffect(()=>{
    getArticleTagListApi().then(res=>{
      console.log(res.data)
      /* [
        {
          value:'',
          label:''
        }
      ] */
      // setTagList(res.data)
      const newTagList = res.data.map(item=>{
        return {
          value:item.name,
          label:item.name
        }
      })
      setTagList(newTagList)
    })
  },[])


  // 提交表单数据的方法
  const onFinish = async(values: any) => {
    console.log(values,articleContent,22222);
    // 添加"authorId":47529555
    // values.article['authorId'] = 47529555
    values.article.authorId = 47529555   // 必填项
    values.article.categoryList = [values.article.categoryList]  // 标签必须是数组结构
    values.article.tagList = [values.article.tagList] // 分类也必须是数组结构
    // console.log(values.article);
    // 对文章内容的非空判断  
    if(articleContent === '' || articleContent === '<p></p>\n'){
      message.error('文章内容不能为空')
      return  // 终止后面的代码的执行
    }
    // 添加文章内容
    values.article.content = articleContent

   try {
    const res = await addArticleApi(values.article)
    if(res && res.status === 200){
      message.success('添加文章成功')
      setTimeout(()=>{
        navigate('/sys/home/list')
      },1000)
    }
    
   } catch (error) {
    // console.log(error)
    message.error(error.response.data.message)
   }
  };



  return (
      <Form
      {...layout}
      name="nest-messages"
      onFinish={onFinish}
      validateMessages={validateMessages}
    >
      <Form.Item name={['article', 'title']} label="文章标题" rules={[{ required: true }]}>
        <Input />
      </Form.Item>
      <Form.Item name={['article', 'tagList']} label="文章标签" rules={[{ required: true }]}>
        <Select
        options={tagList}
      />
      </Form.Item>
      <Form.Item name={['article', 'categoryList']} label="文章分类" rules={[{ required: true }]}>
        <Input />
      </Form.Item>
      <Form.Item name={['article', 'content']} label="文章内容">
        {/* <Input.TextArea /> */}
        <NewsEditor getArticleContent={(value)=>{
          // console.log(value,1111)
          setArticleContent(value)
        }} ></NewsEditor>
      </Form.Item>
      <Form.Item label={null}>
        <Button type="primary" htmlType="submit">
          提交
        </Button>
      </Form.Item>
    </Form>
  )
};

export default Add;